<template>
  <div class="homeContent relposition">
      <!-- v-for循环服务类别 -->
      <div class="top-container pt40 pl300 pr300">
          <div class="row-start-col-center wrap">
              <div v-for="item,index in serviceTypeData" :key="index" class="mt10 shopTypeCard" @click="openNew(item)">
                  <div class="row-center-col-center showMouse" :class="backgroundClass(item,index)">
                      <div class="icon showMouse">
                          <icon-font size="50"  :class="[item.icon]" />
                      </div>
                      <div class="ml10 fs16 showMouse maxwidth100">
                        <span>{{item.productTypeName}} </span>
                      </div>
                  </div>
              </div>
          </div>
          <div class="card-detail mt25 row-start-col-center pd20">
            <div v-if="selectedItem">
                <p><span class="fwbold color-primary">【{{selectedItem.productTypeName}}】</span></p>
                <p v-html="selectedItem?.productTypeDetail || serviceTypeData[0]?.productTypeDetail"> </p>
            </div>
          </div>
      </div>
      <div class="samllPerson showMouse" @click="gotoCompanyList">
         <img src="~@/assets/image/pointer.png" alt="" style="width:100%;heigth:auto">
         <div class="wordcard">
             通用券服务商
         </div>
      </div>
      <div class="bg-gray pl300 pr300 pt20 pb20">
          <!-- 排序条件和服务名称搜索 -->
          <div class="row-spaceb-col-center mt20">
            <el-button-group>
              <el-button
                :type="selectedSortOption === 1 ? 'primary' : ''"
                @click="selectSortOption(1)"
                :icon="getIcon(1)"
              >
                销量
              </el-button>
              <el-button
                :type="selectedSortOption === 2 ? 'primary' : ''"
                @click="selectSortOption(2)"
                :icon="getIcon(2)"
              >
                价格
              </el-button>
              <el-button
                :type="selectedSortOption === 3 ? 'primary' : ''"
                @click="selectSortOption(3)"
                :icon="getIcon(3)"
              >
                销售额
              </el-button>
            </el-button-group>
            <!-- 添加数字化转型相关筛选 -->
            <div v-if="selectedItem?.productTypeId === '33ac82ab-3ab4-46ce-bfd7-105fc62c4eac'" 
                class="digital-filters row-start-col-center ml10">
              <el-select
                v-model="digitalSubtype"
                size="small"
                clearable
                placeholder="数字化产品类型"
                @change="searchKey"
                class="mr10"
              >
                <el-option
                  v-for="item in digitalSubtypeOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
              
              <el-select
                v-model="digitalIndustry"
                size="small"
                clearable
                placeholder="数字化行业"
                @change="searchKey"
                class="mr10"
              >
                <el-option
                  v-for="item in digitalIndustryOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
              
              <el-select
                v-model="digitalScenarios"
                size="small"
                clearable
                placeholder="数字化场景"
                @change="searchKey"
                class="mr10"
              >
                <el-option
                  v-for="item in digitalScenariosOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </div>
            <div class="row-start-col-center">
              <div class="price-range mr10">
                  <el-input 
                    size="small" 
                    v-model="limitPrice" 
                    placeholder="最低价格(元)"
                    class="price-input"
                    clearable
                    @keyup.enter.native="searchKey"
                  >
                  </el-input>
                  <span class="mx5">-</span>
                  <el-input 
                    size="small" 
                    v-model="upperPrice" 
                    placeholder="最高价格(元)"
                    class="price-input"
                    clearable
                    @keyup.enter.native="searchKey"
                  >
                  </el-input>
                </div>
                <el-input size="small" clearable placeholder="请输入服务名关键字" v-model="searchKeyword" @keyup.enter.native="searchKey" class="input-with-select"></el-input>
                <el-button size="small" class="ml10" icon="el-icon-search" @click="searchKey"></el-button>
                <el-button size="small" plain class="ml10" @click="searchAll">全部</el-button>
            </div>
          </div>
          <!-- v-for循环生成卡片式服务列表 -->
          <el-empty v-if="cardList.length === 0" :image-size="200"></el-empty>
          <div v-else class="row-start wrap width-24">
              <div v-for="item,index in cardList" :key="index" class="mt10 shoppingCard" @click="gotoProductDetal(item)">
                  <div class="bg-white showMouse card-shadow pl5 pr5 pt5 pb20 mb40 relposition">
                      <!-- <div v-if="item.upperDiscount > 0" class="absposition"> -->
                      <div class="absposition">
                        <img v-if="item.parentProductTypeId === '1'" src="~@/assets/image/badge.png" style="width:92px;height:28px" alt="">
                        <img v-if="item.parentProductTypeId === '2'" src="~@/assets/image/badge2.png" style="width:92px;height:28px" alt="">
                      </div>
                      <div class="productImage">
                          <img :src="`/api/public/file/v1/public/get/${item.productImg}`" class="comIntro" style="max-width:100%; max-height:100%; object-fit:contain;" alt="" @error="setDefaultImage">
                      </div>
                      <!-- 单价 -->
                      <div class="mt20 ml10 fs18 color-red fwbold">
                        <span>{{$priceFormat(item.limitPrice, item.upperPrice)}} 元 </span>
                      </div>
                      <!-- 服务名称 -->
                      <div v-if="item.parentProductTypeId === '1'"  class="mt5 ml10 color-grey fs12">
                        平台销售价:<span style="text-decoration: line-through">{{$priceFormat(item.limitOriginalPrice, item.upperOriginalPrice)}} 元 </span>
                      </div>
                      <!-- 服务名称 -->
                      <div class="mt10 ml10 fs15">
                        <span>{{item.productName}} </span>
                      </div>
                      <div class="row-spaceb mt10 mr10">
                          <!-- 评分 -->
                          <div class="mt10 ml10 fs12">
                            <span class="color-red">评分：{{item.score || '-'}} </span>
                            <span class="color-grey ml30">交易次数：{{item.transNum || 0}} </span>
                          </div>
                          <!-- 交易次数 -->
                          <div class="ml10 fs12">
                            <el-button plain size="mini" style="color:blue" @click="gotoProductDetal(item)">详情</el-button>
                          </div>
                      </div>
                  </div>
              </div>
          </div>
          <div class="row-end mt20 mb20">
              <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[12, 20, 32, 40]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
              </el-pagination>
          </div>
      </div>
  </div>
</template>

<script>
import { getProductList,getProductTypeList,productSearch } from '@/api/homeApi'
export default {
  name: 'productList',
  components: {
 
  },
  data () {
    return {
       searchKeyword: null,
       selectedItems: [],
       selectedItem: {
        productTypeName:'企业诊断'
       },
       previousSelectedItem: {
        productTypeName:'企业诊断'
       },
       typeList:[
            {name:'企业诊断',icon:'icon-a-01qiyezhenduan',type:1},
            {name:'数字化转型',icon:'icon-a-03shuzihuazhuanxing', type:2},
            {name:'技术创新',icon:'icon-a-05jishuchuangxin',type:3},
            {name:'管理咨询',icon:'icon-a-07guanlizixun',type:4},
            {name:'市场开拓',icon:'icon-a-09shichangkaituo',type:5},
            {name:'企业上市',icon:'icon-a-11qiyeshangshi',type:6},
            {name:'融资服务',icon:'icon-a-02rongzifuwu',type:7},
            {name:'检测认证',icon:'icon-a-04jianyanjiance',type:8},
            {name:'法律服务',icon:'icon-a-06falvfuwu',type:9},
            {name:'培训服务',icon:'icon-a-08peixunfuwu',type:10},
            {name:'人力资源',icon:'icon-a-10renliziyuan',type:11},
            {name:'其他服务',icon:'icon-a-12qita',type:12},
       ],
       // 生成一个卡片式数组，包含12个元素，包含服务价格/单位、服务名称、服务评分，交易次数、服务券类型，服务头图
        cardList:[

        ],
        currentPage: 1,
        pageSize: 12,
        total: 10,
        selectedSortOption:null,
        serviceTypeData:[],
        orderBy:0,
        isAsc:true,
        previousSortOption: 1,
        clickCount:0,
        limitPrice:null,
        upperPrice:null,
        digitalSubtype: null,
        digitalIndustry: null, 
        digitalScenarios: null,
        digitalSubtypeOptions: [],
        digitalIndustryOptions: [],
        digitalScenariosOptions: [],
    }
  },
  created () {
    // 获取跳转到服务详情的缓存
    const savedState = sessionStorage.getItem('productListState');
    if (savedState) {
      const state = JSON.parse(savedState);
      this.currentPage = state.currentPage;
      this.pageSize = state.pageSize;
      this.selectedSortOption = state.selectedSortOption;
      this.searchKeyword = state.searchKeyword;
    }
    // 获取服务类型
   this.initDigitalOptions()
   if(this.serviceTypeData.length === 0){
       this.getProductType()
    }
    const query = this.$route.query;
    if (query.companyId) {
       this.search(query.companyId)
    }else{
      this.search()
    }
  },
  computed: {

  },
  methods: {
      initDigitalOptions() {
        for (const item of Object.values(this.$store.getters.commonDict)) {
          if (item.dictType === 'sme_digital_subtype') {
            this.digitalSubtypeOptions = item.dictData;
          }
          if (item.dictType === 'sme_digital_industry') {
            this.digitalIndustryOptions = item.dictData;
          }
          if (item.dictType === 'sme_digital_scenarios') {
            this.digitalScenariosOptions = item.dictData;
          }
        }
      },
      gotoCompanyList(){
        this.$router.push({path:'/serviceCompany',query:{type: 1}})
      },
      backgroundClass(item,index) {
          const isSelected = this.selectedItems.includes(item);
          if (isSelected) {
            if(item.id > 10) {
              return [`backgrounds${item.id-10}`,'h100p']
            };
            return [`backgrounds${item.id}`,'h100p'];
          } else if(index >= 10){
            return [`background${index-9}`,'h100p'];
          } else {
            return [`background${index+1}`,'h100p'];
          }
      },
      setDefaultImage(event) {
        event.target.src = require('@/assets/image/error.jpg');
      },
      searchKey(){
        this.currentPage = 1
        this.search()
      },
      searchAll(){
        this.searchKeyword = '';
        this.currentPage = 1
        this.search()
      },
      search(companyId='') {
        const limitPrice = this.limitPrice > 0 ? this.limitPrice*100 : null
        const upperPrice = this.upperPrice > 0 ? this.upperPrice*100 : null
        let queryParams = {
          isAsc: this.isAsc,
          q: this.searchKeyword,
          pageNo: this.currentPage,
          pageNum: this.pageSize,
          orderBy: this.selectedSortOption,
          companyId:companyId,
          productTypeId:'1',
          limitPrice:limitPrice, 
          upperPrice:upperPrice 
        };
        if (this.selectedItems.length > 0) {
          queryParams.productTypeId = this.selectedItems.map(item => item.productTypeId).join(',');
        }
        // 当选中数字化转型类别时，添加相关筛选条件
        if (this.selectedItem?.productTypeId === '33ac82ab-3ab4-46ce-bfd7-105fc62c4eac') {
          if (this.digitalSubtype) queryParams.digitalSubtype = this.digitalSubtype
          if (this.digitalIndustry) queryParams.digitalIndustry = this.digitalIndustry
          if (this.digitalScenarios) queryParams.digitalScenarios = this.digitalScenarios
        }
        getProductList(queryParams).then(res => {
          if (res.code === 200) {
            this.cardList = res.rows.map(item => {
              let productImg = item.productImg.includes('|') ? item.productImg.split('|')[0] : item.productImg;
              return {
                ...item,
                productImg: productImg
              }
            });
            this.total = res.total;
          }
        })
      },
      getProductType() {
        getProductTypeList({level:2,parentId:'1'}).then(res => {
          if (res.code === 200) {
            this.serviceTypeData = res.data.map((item,index) => {
              return {
                ...item,
                icon: this.typeList[index].icon,
                id: index+1,
              }
            });
          }
        })
      },
      gotoDetail(){
        this.$router.push({path:'/productDetail'})
      },
      clearSearch() {
        this.searchKeyword = '';
        // 在这里添加你的搜索逻辑
      },
      handleClick(event) {
      // 阻止事件冒泡
      event.stopPropagation();
      console.log('event',event);
        // 处理点击事件，例如调用 selectSortOption 方法
        this.selectSortOption(this.selectedSortOption);
      },
      selectSortOption(option) {
            this.selectedSortOption = option;
            this.isAsc = false;
            this.clickCount++;
            if(this.previousSortOption!== this.selectedSortOption){
               this.clickCount = 1
            }
            if (this.selectedSortOption === option) {
              if (this.clickCount === 1) {
                // First click: descending order
                this.isAsc = false;
              } else if (this.clickCount === 2) {
                // Second click: ascending order
                this.isAsc = true;
              } else {
                // Third click: reset sorting
                this.selectedSortOption = null;
                this.isAsc = true;
                this.clickCount = 0;
                this.previousSortOption = null; // Reset previous option
              }
            }
            this.search();
            if (this.selectedSortOption !== null) {
              this.previousSortOption = option;
            }
      },
      getIcon(option) {
        if (this.selectedSortOption !== option) {
          return 'el-icon-sort';
        }
        return this.clickCount === 1 ? 'el-icon-sort-down' : 'el-icon-sort-up';
      },
      openNew(item) {
        const index = this.selectedItems.indexOf(item);
        if (index !== -1) {
          // If the item is already selected, deselect it
          this.selectedItems.splice(index, 1);
          this.selectedItem = this.selectedItems.length > 0 ? this.selectedItems[this.selectedItems.length - 1] : null;
        } else {
          // If the item is not selected, add it to the selection
          this.selectedItems.push(item);
          this.selectedItem = item;
        }
          // Prepare query parameters
        // let queryParams = {
        //   isAsc: this.isAsc,
        //   keyword: this.searchKeyword,
        //   pageNo: this.currentPage,
        //   pageNum: this.pageSize,
        //   orderBy: this.selectedSortOption,
        //   productTypeId:'1'
        // };
        // if (this.selectedItems.length > 0) {
        //   queryParams.productTypeId = this.selectedItems.map(item => item.productTypeId).join(',');
        // }
        // getProductList(queryParams).then(res => {
        //   if (res.code === 200) {
        //     this.cardList = res.rows.map(item => {
        //       let productImg = item.productImg.includes('|') ? item.productImg.split('|')[0] : item.productImg;
        //       return {
        //         ...item,
        //         productImg: productImg
        //       }
        //     });
        //     this.total = res.total;
        //   }
        // })
        this.currentPage = 1
        this.search()
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pageSize = val;
        this.search()
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.currentPage = val;
        this.search()
      },
      gotoProductDetal(item){
        window.scrollTo(0, 0);
        sessionStorage.setItem('productListState', JSON.stringify({
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          selectedSortOption: this.selectedSortOption,
          searchKeyword: this.searchKeyword
        }));
        this.$router.push({path:'/productDetail',query:{type:item.name,id:item.productId}})
      }
  }

}
</script>

<style scoped>
.top-container{
  width: 100%;
  min-height: 300px;
  background: #fff;
  background-size: cover;
  position: relative;
  margin-top: 2px;
}
.samllPerson{
  position: absolute;
  top: 50px;
  right:6%;
}
.wordcard{
  background: #4269F6;
  color: #fff;
  border: 1px solid #FFFFFF;
  width: 130px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  border-radius: 5px;
}
.pl300{
  padding-left: 15%;
}
.pr300{
  padding-right: 15%;
}
.sortOption {
  cursor: pointer;
  color: #999;
}

.sortOption .selected {
  color: #333;
}
.homeContent{
    width: 100%;
    min-height:80vh;
    margin: 0 auto;
}
.border{
    border: 1px solid #ccc;
}
.comIntro{
  width: 100%;
}
  .maxwidth100{
    max-width: 80px;
    word-wrap: break-word;
  }
.shopTypeCard{
  flex: 0 0 calc((100% - 90px) / 7);
  aspect-ratio: 3 / 1;
  box-sizing: border-box;
  background-size: 100% 100%;
  border-radius: 5px 5px 5px 5px;
  color: #436AF7;
  align-items: center;
}
.shopTypeCard:nth-child(n) {
  margin-right: 15px;
}
.shopTypeCard:nth-child(7n) {
  margin-right: 0px;
}
/* .shopTypeCard:hover {
  background: #436AF7;
  color: #FFFFFF;
} */
/* .showMouse:hover {
  transform: scale(1.1);
  transition: transform 0.3s;
} */
.card-detail{
  background-image: url('~@/assets/image/type_detail.png');
  background-size: 100% 100%;
  height: 140px;
  width: 100%;
}
.shoppingCard{
  flex: 0 0 calc((100% - 150px) / 4);
  margin-left: 25px;
  margin-right: 25px;
  box-sizing: border-box;
}
.shoppingCard:nth-child(4n + 1) {
  padding-left: 0;
  margin-left: 0px;
}
.shoppingCard:nth-child(4n) {
  padding-right: 0;
  margin-right: 0px;
}
.cardtype{
  background-color:rgb(237,123,89) ;
  color:#fff ;
  padding: 5px;
  border-radius:0px 0px 10px 0px;
  top: 5px;
  left: 5px;
}
.selected {
  background-image: url('~@/assets/image/typebgs1.png');
  background-size: 100% 100%;
  color: #FFFFFF;
}
.selectedText {
  color: #333;
}
.carouselTitle{
  top:50px;
  left: 130px;
  width: 400px;
  height: 129px;
  font-family: Alibaba PuHuiTi, Alibaba PuHuiTi;
  font-weight: 500;
  font-size: 50px;
  color: #FFFFFF;
  line-height: 60px;
  text-align: left;
  z-index: 99;
}
.button1{
  width: 150px;
  height: 50px;
  background: #FFFFFF;
  border-radius: 5px 5px 5px 5px;
  border: 1px solid #436AF7;
  color: #436AF7;
  font-size: 18px;
  margin-right:40px;
}
.button2{
  width: 262px;
  height: 50px;
  background: #436AF7;
  border-radius: 5px 5px 5px 5px;
  font-size: 18px;
  border: 1px solid #436AF7;
  }
 .background1 {
  background-image: url('~@/assets/image/typebg1.png');
  background-size: 100% 100%;
  }
 .backgrounds1 {
  background-image: url('~@/assets/image/typebgs1.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
 .background2 {
  background-image: url('~@/assets/image/typebg2.png');
   background-size: 100% 100%;
  }
 .backgrounds2 {
  background-image: url('~@/assets/image/typebgs2.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .background3 {
  background-image: url('~@/assets/image/typebg3.png');
   background-size: 100% 100%;
  }
 .backgrounds3 {
  background-image: url('~@/assets/image/typebgs3.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .background4 {
  background-image: url('~@/assets/image/typebg4.png');
  background-size: 100% 100%;
  }
  .backgrounds4 {
  background-image: url('~@/assets/image/typebgs4.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .background5 {
  background-image: url('~@/assets/image/typebg5.png');
  background-size: 100% 100%;
  }
  .backgrounds5 {
  background-image: url('~@/assets/image/typebgs5.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .background6 {
  background-image: url('~@/assets/image/typebg6.png');
  background-size: 100% 100%;
  }
  .backgrounds6 {
  background-image: url('~@/assets/image/typebgs6.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .background7 {
  background-image: url('~@/assets/image/typebg7.png');
  background-size: 100% 100%;
  }
  .backgrounds7 {
  background-image: url('~@/assets/image/typebgs7.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .background8 {
  background-image: url('~@/assets/image/typebg8.png');
  background-size: 100% 100%;
  }
  .backgrounds8 {
  background-image: url('~@/assets/image/typebgs8.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .background9 {
  background-image: url('~@/assets/image/typebg9.png');
  background-size: 100% 100%;
  }
  .backgrounds9 {
  background-image: url('~@/assets/image/typebgs9.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .background10 {
  background-image: url('~@/assets/image/typebg10.png');
  background-size: 100% 100%;
  }
  .backgrounds10 {
  background-image: url('~@/assets/image/typebgs10.png');
  background-size: 100% 100%;
  color: #FFFFFF;
  }
  .productImage{
    width:100%; 
    aspect-ratio: 1.5 / 1;
    display:flex; 
    justify-content:center; 
    align-items:center;
    background-image: url('~@/assets/image/productBg.png');
    background-size: 100% 100%;
  }
.price-range {
  display: flex;
  align-items: center;
}
.price-input {
  width: 120px;
}
.mx5 {
  margin: 0 5px;
}
.digital-filters {
  display: flex;
  align-items: center;
}
.digital-filters .el-select {
  width: 150px;
}
</style>
